#include "protocol.h"

SLN* BuyNode(int sockfd)
{
    SLN* node=(SLN*)malloc(sizeof(SLN));
    if(node==NULL)
    {
        perror("malloc");
        exit(1);
    }
    node->_sockfd=sockfd;
    node->_prev=NULL;
    node->_next=NULL;
    return node;
}

SLN* phead=NULL;

int ServerDo()
{
    int fd=socket(AF_INET,SOCK_STREAM,0);
    if(fd<0)
    {
        perror("socket");
        exit(2);
    }
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(PORT);
    server.sin_addr.s_addr=inet_addr(IP);

    if(bind(fd,(struct sockaddr*)&server,sizeof(server))<0)
    {
        perror("bind");
        exit(3);
    }
    if(listen(fd,5)<0)
    {
        perror("listen");
        exit(4);
    }
    return fd;
}

void func(void* arg)
{
    SLN* node=(SLN*)arg;
    SLN* cur=NULL;
    char buf[NAME+MSG]={0};
    while(1)
    {
        ssize_t rec=recv(node->_sockfd,buf,NAME+MSG,0);
        if(rec<=0)
        {
            printf("sockfd closed\n");
            break;
        }
        cur=phead->_next;
        while(cur!=NULL)
        {
            send(cur->_sockfd,buf,NAME+MSG,MSG_DONTWAIT);
            cur=cur->_next;
        }
    }

    node->_prev->_next=node->_next;
    if(node->_next!=NULL)
    {
        node->_next->_prev=node->_prev;
    }
    node->_prev=NULL;
    node->_next=NULL;
    free(node);
    close(node->_sockfd);
}
[root@VM_0_4_centos 1.tcp群聊]# cat client.c
#include "protocol.h"

int ClientDo(char* argv[])
{
   int fd=socket(AF_INET,SOCK_STREAM,0);
   if(fd<0)
   {
       perror("socket");
       exit(2);
   }
   struct sockaddr_in server;
   server.sin_family=AF_INET;
   server.sin_port=htons(PORT);
   server.sin_addr.s_addr=inet_addr(PIP);
   if(connect(fd,(struct sockaddr*)&server,sizeof(server))<0)
   {
       perror("connect");
       exit(3);
   }
   return fd;
}

void working(int sockfd,char* name)
{
    if(fcntl(0,F_SETFL,FNDELAY)<0)
    {
        perror("fcntl");
        exit(4);
    }
    user u;
    char buf[NAME+MSG]={0};

    while(1)
    {
        strncpy(buf,name,NAME);

        ssize_t r=read(0,u._msg,MSG);
        if(r>0)
        {
            u._msg[r]=0;
            fflush(stdout);
            strcpy(buf+NAME,u._msg);
            send(sockfd,buf,NAME+MSG,MSG_DONTWAIT);
        }
        ssize_t rec=recv(sockfd,buf,NAME+MSG,MSG_DONTWAIT);
        if(rec>0)
        {
            strncpy(u._name,buf,NAME);
            strncpy(u._msg,buf+NAME,MSG);
            printf("%s :>%s",u._name,u._msg);
        }
    }
    close(sockfd);
}

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        printf("parameter is too less\n");
        return 1;
    }

    int sockfd=ClientDo(argv);

    working(sockfd,argv[1]);

    return 0;
}